package cn.lvji.sus.api;

import cn.lvji.sus.CreateResponse;
import cn.lvji.sus.GetSPIMaps;
import cn.lvji.sus.LongToShortAlgorithm;
import cn.lvji.sus.Maps;
import cn.lvji.sus.db.JDBCUtils;
import cn.lvji.sus.model.Links;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mysql.jdbc.StringUtils;
import org.slf4j.Logger;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * 生产短链API
 *
 * @author zhouzx
 */
@WebServlet(name = "create", urlPatterns = "/create")
public class RestApi implements Servlet {
    private static final Logger logger = getLogger(RestApi.class);
    private Maps urlMaps;

    @Override
    public void init(ServletConfig config) {
        logger.info("create servlet creating!");
        this.urlMaps = GetSPIMaps.getMaps();
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        request.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json; charset=UTF-8");
        String token = request.getHeader("token");
        CreateResponse createResponse = new CreateResponse();
        if (token == null || "".equals(token.trim())) {
            createResponse.setCode(401);
            createResponse.setMsg("token不合法！");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response(createResponse, response);
            return;
        }


        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        Gson gson = new Gson();
        JsonObject longRequest = gson.fromJson(sb.toString(), JsonObject.class);
        String longUrl = longRequest.get("url").getAsString();
        if (!validate(longUrl)) {
            createResponse.setCode(400);
            createResponse.setMsg("长链接不合法！");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response(createResponse, response);
            return;
        }

        String shortUrl = LongToShortAlgorithm.shortUrl(longUrl);
        urlMaps.addUrl(longUrl, shortUrl);
        createResponse.setLongUrl(longUrl);
        createResponse.setShortUrl(shortUrl);
        Links links = new Links(longUrl, shortUrl);
        JDBCUtils.addLink(links);
        response(createResponse, response);
    }


    private void response(CreateResponse createResponse, HttpServletResponse response) {
        Gson gson = new Gson();
        try (PrintWriter writer = response.getWriter()) {
            writer.println(gson.toJson(createResponse));
            writer.flush();
        } catch (Exception e) {
            logger.error("flush response error", e);
        }
    }

    /**
     * 长连接校验
     * TODO 域名安全性校验等
     *
     * @param longUrl 长链接
     * @return 是否合法并安全
     */
    private boolean validate(String longUrl) {
        return !StringUtils.isNullOrEmpty(longUrl) && (longUrl.startsWith("http://") || longUrl.startsWith("https://"));
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {
        logger.warn("create servlet destroying!");
    }
}
